import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:window_manager/window_manager.dart';
import '../../config/kq_global.dart';
import '../../resources/kq_theme_colors.dart';

import '../../resources/images.dart';
import '../../theme/kq_theme_manager.dart';
import '../button/kq_head_button.dart';
import '../button/kq_ink_well.dart';
import '../dropDownMenu/kq_drop_down_menu.dart';
import '../searchBar/kq_search_bar.dart';

/// 通用AppBar
/// K6 搬过来的
class KqHeadBar extends KqAppBar {
  /// KqHeadBar--标题
  final String? headTitle;

  /// 背景颜色
  final Color? bgColor;

  /// 是否显示下拉图标
  final bool showDropIcon;

  /// 标题点击回调
  final VoidCallback? onTapTitle;

  /// 标题下拉菜单数据菜单列表
  final List<KqDropMenuData>? dropMenuData;

  /// 下拉菜单控制器
  final KqDropDownMenuController? menuController;

  /// 标题下拉菜单选中回调，返回true，表示可以选中
  final Function(KqDropMenuData menuData)? onSelected;

  /// 字体颜色
  final Color? color;

  /// 返回按钮的图标，自定义 [KqHeadButton] 里面的 [widget] 属性
  final Widget? backIcon;

  /// 返回提示文字
  final String? backTooltip;

  /// 是否展示左侧返回按钮
  final bool showBack;

  /// KqHeadBar--右侧自定义区域，如无特殊情况，请统一使用[KqHeadButton]
  @override
  final dynamic actions;

  /// 自定义返回事件
  final VoidCallback? back;

  /// 自定义标题控件
  final Widget? customTitle;

  /// 标题栏显示形态
  final TitleBarShowMode showMode;

  /// 自定义搜索框左边控件
  final Widget? customSearchLeftWidget;

  /// 自定义搜索框右边控件
  final Widget? customSearchRightWidget;

  /// 取消搜索回调
  final Function()? onCancelSearch;

  /// 数值变化监听
  final ValueChanged<String>? onSearchChanged;

  /// 搜索回调（包括扫码枪和软键盘的提交）
  final Function(String value, KqSearchBarState state)? onSearchSubmit;

  /// 用于监听停顿回调，基于onTextChange，500ms没有输入则回调，避免频繁调用接口。
  final Function(String str)? onSearchMonitor;

  /// 清空按钮点击监听
  final VoidCallback? onSearchCleared;

  /// 搜索hint
  final String? placeHolder;

  /// 搜索输入框TextEditingController
  final TextEditingController? editingController;

  /// 搜索取消按钮提示文字
  final String? cancelBtnTooltip;

  final double? titleHorizontalPadding;

  const KqHeadBar({
    super.key,
    this.headTitle,
    this.actions,
    super.iconColor,
    this.backIcon,
    this.back,
    this.bgColor,
    this.showDropIcon = false,
    this.dropMenuData,
    this.menuController,
    this.onSelected,
    this.onTapTitle,
    this.customTitle,
    this.placeHolder,
    this.editingController,
    this.color,
    this.showBack = true,
    this.customSearchLeftWidget,
    this.customSearchRightWidget,
    this.onSearchChanged,
    this.onSearchSubmit,
    this.onSearchMonitor,
    this.onSearchCleared,
    this.backTooltip,
    this.cancelBtnTooltip,
    this.titleHorizontalPadding,
    super.statusBarColor,
    super.statusBarMaskColor,
    super.statusBarIconColor,
    super.titleAlign,
    super.actionSpacing,
    super.leftAction,
    this.showMode = TitleBarShowMode.normal,
    this.onCancelSearch,
    super.hideWindowIcon,
    super.hideWindowsIconBar,
  })  : assert(
            actions == null || actions is Widget || (actions is List<Widget>)),
        super(title: headTitle, actions: actions);

  @override
  Widget build(BuildContext context) {
    return DefaultTextStyle(
      style: TextStyle(color: color ?? KqThemeColors.bgWhite),
      child: KqAppBar(
          //默认显示返回按钮
          backgroundColor:
              bgColor ?? KqThemeManager.getCommonConfig().mainColor,
          iconColor: iconColor,
          isSearchMode: showMode == TitleBarShowMode.search,
          title: showMode == TitleBarShowMode.normal
              ? customTitle ??
                  KqAppBarTitle(headTitle ?? '',
                      showDropIcon: showDropIcon,
                      onTapTitle: onTapTitle,
                      textStyle: TextStyle(
                        fontSize: 18,
                        color: color ?? KqThemeColors.bgWhite,
                      ),
                      titleAlign: titleAlign,
                      titleHorizontalPadding: titleHorizontalPadding ?? 0,
                      dropMenuData: dropMenuData,
                      onSelected: onSelected,
                      menuController: menuController)
              : KqSearchBar(
                  outerBgColor: KqThemeColors.bgTransparent,
                  innerBgColor: KqThemeColors.bgTransparent,
                  outHeight: 40,
                  searchIconColor: iconColor ?? KqThemeColors.bgWhite,
                  cursorColor: color ?? KqThemeColors.bgWhite,
                  alwaysShowCancelBtn: true,
                  fontSize: 14,
                  cancelTextColor: color ?? KqThemeColors.bgWhite,
                  textColor: color ?? KqThemeColors.bgWhite,
                  placeHolderTextColor: KqThemeColors.bgD,
                  hintText: placeHolder,
                  customLeftWidget: customSearchLeftWidget,
                  customRightWidget: customSearchRightWidget,
                  editController: editingController,
                  unFocusWhenCleared: false,
                  onChanged: onSearchChanged,
                  onSubmit: onSearchSubmit,
                  onCleared: onSearchCleared,
                  customLeftIcon: Icon(
                    Icons.search,
                    color: iconColor ?? KqThemeColors.bgWhite,
                    size: 20,
                  ),
                  cancelBtnTooltip: cancelBtnTooltip,
                  onMonitor: onSearchMonitor,
                  autofocus: true,
                  onCancel: onCancelSearch,
                ),
          hideWindowIcon: hideWindowIcon,
          hideWindowsIconBar: hideWindowsIconBar,
          statusBarColor: statusBarColor,
          statusBarMaskColor: statusBarMaskColor,
          statusBarIconColor: statusBarIconColor,
          titleAlign: titleAlign,
          leftAction: leftAction,
          actionSpacing: actionSpacing,
          leading: showMode == TitleBarShowMode.normal && showBack
              ? KqHeadButton(
                  widget: backIcon ??
                      Icon(
                        Icons.arrow_back_ios,
                        size: 20,
                        color: iconColor ?? KqThemeColors.bgWhite,
                      ),
                  tooltip: backTooltip ?? '返回',
                  onTap: back ?? Get.back,
                )
              : null,
          actions: showMode == TitleBarShowMode.normal ? actions : null),
    );
  }
}

enum TitleBarShowMode {
  /// 普通状态
  normal,

  /// 搜索状态
  search
}

class KqAppBar extends StatelessWidget implements PreferredSizeWidget {
  /// 导航栏左侧活动区域,在为null且
  final Widget? leading;

  /// AppBar标题,必须是String或者Widget类型
  /// 为String时,会使用[KqAppBarTitle]来加载title
  final dynamic title;

  /// 为了方便业务使用，可以设置为Widget或者List<Widget>
  /// 传入的Widget会自动添加边距并转化为List<Widget>
  /// 传入的List<Widget>会自动添加右边距和action之间的间距
  final dynamic actions;

  /// 左侧的Action，位于返回按钮右侧，只能有一个
  final Widget? leftAction;

  /// 以下属性都对应于[AppBar]中的属性
  /// 详细介绍可以查阅[AppBar]的文档
  final Color? backgroundColor;
  final double elevation;
  final double? leadingWidth;

  /// 状态栏颜色
  final Color? statusBarColor;

  /// 状态栏遮罩颜色
  final Color? statusBarMaskColor;

  /// 状态栏图标颜色
  final Color? statusBarIconColor;

  /// 搜索模式
  final bool isSearchMode;

  /// 图标颜色
  final Color? iconColor;

  /// 标题对齐方式
  final Alignment? titleAlign;

  /// 是否隐藏窗口按钮（最大化，最小化，关闭），默认false，
  final bool hideWindowIcon;

  final double? actionSpacing;

  /// 是否彻底隐藏顶部的窗口按钮（最大化，最小化，关闭），包括高度，默认false
  final bool hideWindowsIconBar;

  const KqAppBar({
    super.key,
    this.leading,
    this.title,
    this.actions,
    this.backgroundColor,
    this.iconColor,
    this.elevation = 0,
    this.statusBarColor,
    this.statusBarMaskColor,
    this.statusBarIconColor,
    this.leadingWidth,
    this.titleAlign,
    this.actionSpacing,
    this.leftAction,
    this.hideWindowsIconBar = false,
    this.isSearchMode = false,
    this.hideWindowIcon = false,
  })  : assert(
            actions == null || actions is Widget || (actions is List<Widget>)),
        assert(title == null || title is String || title is Widget);

  @override
  Size get preferredSize {
    return Size.fromHeight(appBarHeight());
  }

  @override
  Widget build(BuildContext context) {
    var buildAppBarTitle = _buildAppBarTitle();

    var wrapActions = _wrapActions();

    var wrapLeading = _wrapLeading();

    var leadingSize = _culLeadingSize();

    var barHeight = appBarHeight();

    Widget child = SizedBox(
      height: Platform.isWindows ? 40 : barHeight,
      child: Stack(
        children: [
          Positioned(
              left: 0,
              right: 0,
              top: Platform.isWindows
                  ? 0
                  : KqThemeManager.getCommonConfig().titleBarHeight ?? 0,
              bottom: 0,
              child: Row(
                children: [
                  if (wrapLeading != null) wrapLeading,
                  const Spacer(),
                  if (wrapActions != null) ...wrapActions,
                ],
              )),
          if (buildAppBarTitle != null)
            Positioned(
                left: leadingSize,
                right: leadingSize,
                top: Platform.isWindows
                    ? 0
                    : KqThemeManager.getCommonConfig().titleBarHeight ?? 0,
                bottom: 0,
                child: Align(
                  alignment: titleAlign ?? Alignment.center,
                  child: buildAppBarTitle,
                )),
        ],
      ),
    );

    if (Platform.isWindows && !hideWindowsIconBar) {
      child = Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          DragToMoveArea(
            child: Stack(
              children: [
                Container(
                  height: KqThemeManager.getCommonConfig().titleBarHeight ?? 0,
                  color: statusBarColor ??
                      KqThemeManager.getCommonConfig().mainColor,
                  alignment: Alignment.centerRight,
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      if (!hideWindowIcon)
                        KqInkWell(
                            enableRipple: false,
                            hoverColor: KqThemeColors.bgWhite.withOpacity(0.2),
                            onTap: () {
                              windowManager
                                  .minimize()
                                  .onError((error, stackTrace) {});
                            },
                            tooltip: '最小化',
                            child: SizedBox(
                              width: KqThemeManager.getCommonConfig()
                                      .titleBarHeight ??
                                  0,
                              height: KqThemeManager.getCommonConfig()
                                      .titleBarHeight ??
                                  0,
                              child: Align(
                                child: Image.asset(
                                  Images.commonIcMin,
                                  width: 22,
                                  height: 22,
                                  color: statusBarIconColor,
                                  package: KqGlobal.packageName,
                                ),
                              ),
                            )),
                      if (!hideWindowIcon)
                        KqInkWell(
                            enableRipple: false,
                            hoverColor: KqThemeColors.bgWhite.withOpacity(0.2),
                            onTap: () {
                              windowManager.isMaximized().then((value) {
                                if (value) {
                                  windowManager
                                      .unmaximize()
                                      .onError((error, stackTrace) {});
                                } else {
                                  windowManager
                                      .maximize()
                                      .onError((error, stackTrace) {});
                                }
                              }).onError((error, stackTrace) {});
                            },
                            tooltip: '最大化',
                            child: SizedBox(
                              width: KqThemeManager.getCommonConfig()
                                      .titleBarHeight ??
                                  0,
                              height: KqThemeManager.getCommonConfig()
                                      .titleBarHeight ??
                                  0,
                              child: Align(
                                child: Image.asset(
                                  Images.commonIcMax,
                                  width: 22,
                                  height: 22,
                                  color: statusBarIconColor,
                                  package: KqGlobal.packageName,
                                ),
                              ),
                            )),
                      if (!hideWindowIcon)
                        KqInkWell(
                            enableRipple: false,
                            hoverColor: Colors.red,
                            onTap: () {
                              windowManager
                                  .close()
                                  .onError((error, stackTrace) {});
                            },
                            tooltip: '关闭窗口',
                            child: SizedBox(
                              width: KqThemeManager.getCommonConfig()
                                      .titleBarHeight ??
                                  0,
                              height: KqThemeManager.getCommonConfig()
                                      .titleBarHeight ??
                                  0,
                              child: Align(
                                child: Image.asset(
                                  Images.commonIcClose,
                                  width: 22,
                                  height: 22,
                                  color: statusBarIconColor,
                                  package: KqGlobal.packageName,
                                ),
                              ),
                            )),
                    ],
                  ),
                ),
                if (statusBarMaskColor != null)
                  Positioned.fill(
                      child: Container(
                    color: statusBarMaskColor,
                  ))
              ],
            ),
          ),
          child,
        ],
      );
    }

    return Material(
      elevation: elevation,
      color: Colors.transparent,
      child: IconTheme(
        data:
            IconThemeData(color: iconColor ?? KqThemeColors.bgWhite, size: 20),
        child: Container(
          width: double.infinity,
          color: backgroundColor ??
              KqThemeManager.getCommonConfig().mainColor ??
              KqThemeColors.bgBlue,
          child: child,
        ),
      ),
    );

    // return AppBar(
    //   key: key,
    //   leading: _wrapLeading(),
    //   leadingWidth: leadingWidth ?? _culLeadingSize(),
    //   titleSpacing: 0,
    //   automaticallyImplyLeading: false,
    //   title: _buildAppBarTitle(),
    //   centerTitle: true,
    //   elevation: elevation,
    //   backgroundColor: backgroundColor,
    //   actions: _wrapActions(),
    //   systemOverlayStyle: SystemUiOverlayStyle.light,
    //   scrolledUnderElevation: 0,
    //   shadowColor: shadowColor,
    //   primary: primary,
    //   excludeHeaderSemantics: excludeHeaderSemantics,
    // );
  }

  // 根据输入的leading 设置默认的leadingWidth
  double _culLeadingSize() {
    if (leadingWidth != null) {
      return leadingWidth!;
    }
    if (leading == null) {
      return 0;
    }
    return 20 + 40 + (leftAction == null ? 0 : 40);
  }

  double appBarHeight() {
    return 40 + (KqThemeManager.getCommonConfig().titleBarHeight ?? 0);
  }

  // 对[actions]进行包装: 单一的Widget会添加右边距
  //                     List<Widget>在添加右边距的 并 添加action中的间距
  List<Widget>? _wrapActions() {
    if (actions == null || !(actions is List<Widget> || actions is Widget)) {
      return null;
    }
    List<Widget> actionList = <Widget>[];

    if (actions is List<Widget>) {
      if (actions.isEmpty) {
        return actionList;
      }
      List<Widget> tmp = (actions as List<Widget>).map((_) {
        return _;
      }).toList();

      for (int i = 0, n = tmp.length; i < n; i++) {
        actionList.add(tmp[i]);
        if (i != n - 1) actionList.add(SizedBox(width: actionSpacing ?? 8));
      }
    } else {
      Widget realAction = actions;
      actionList.add(realAction);
    }
    return actionList..add(const SizedBox(width: 20));
  }

  // 详情请参考_ToolbarLayout的布局方法
  Widget? _buildAppBarTitle() {
    Widget? realTitle;
    if (title is Widget) {
      return title;
    }
    if (title is String) {
      realTitle = KqAppBarTitle(
        title,
        titleAlign: titleAlign,
        titleHorizontalPadding: titleAlign == Alignment.centerLeft ? 0 : 20,
      );
    }

    return realTitle;
  }

  //添加左边距
  Widget? _wrapLeading() {
    if (leading == null) {
      return null;
    }
    return Container(
      padding: const EdgeInsets.only(left: 20),
      child: Row(
        children: [
          leading!,
          if (leftAction != null)
            SizedBox(width: actionSpacing ?? 8,),
          if (leftAction != null)
            leftAction!,
        ],
      ),
    );
  }
}

/// [KqAppBar.title]的默认实现
/// 标题文字个数限制在15个以内，并且单行展示
class KqAppBarTitle extends StatelessWidget {
  final String title;

  /// 是否显示下拉图标
  final bool showDropIcon;

  final VoidCallback? onTapTitle;

  final TextStyle? textStyle;

  final List<KqDropMenuData>? dropMenuData;

  final KqDropDownMenuController? menuController;

  /// 选中回调，返回true，表示可以选中
  final Function(KqDropMenuData menuData)? onSelected;

  /// 水平间距， 默认20
  final double? titleHorizontalPadding;

  final Alignment? titleAlign;

  const KqAppBarTitle(this.title,
      {Key? key,
      this.textStyle,
      this.showDropIcon = false,
      this.onTapTitle,
      this.onSelected,
      this.menuController,
      this.titleHorizontalPadding,
      this.titleAlign,
      this.dropMenuData})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    Widget titleWidget = !showDropIcon
        ? Container(
            height: appBarHeight(),
            alignment: titleAlign ?? Alignment.center,
            padding: EdgeInsets.only(
                left: titleHorizontalPadding ?? 20,
                right: titleHorizontalPadding ?? 20),
            child: Text(
              title,
              textAlign: TextAlign.center,
              style: textStyle ??
                  const TextStyle(fontSize: 18, fontWeight: FontWeight.normal),
              overflow: TextOverflow.ellipsis,
            ),
          )
        : Container(
            height: appBarHeight(),
            alignment: titleAlign ?? Alignment.center,
            padding: EdgeInsets.only(
                left: titleHorizontalPadding ?? 20,
                right: titleHorizontalPadding ?? 20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                ConstrainedBox(
                  constraints: BoxConstraints(
                      maxWidth: (textStyle?.fontSize ?? 18) *
                          ((showDropIcon ? 12 : 15) + 1)),
                  child: Text(
                    title,
                    // '测试很长的数据测试很长的数据测试很长的数据',
                    textAlign: TextAlign.center,
                    style: textStyle ??
                        const TextStyle(
                            fontSize: 18, fontWeight: FontWeight.normal),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                if (showDropIcon)
                  const SizedBox(
                    width: 4,
                  ),
                if (showDropIcon)
                  Image.asset(
                    Images.commonIcJiantouDown16White,
                    width: 16,
                    height: 16,
                    fit: BoxFit.fill,
                    package: KqGlobal.packageName,
                  ),
              ],
            ),
          );
    if (!showDropIcon) {
      if (onTapTitle == null) {
        return titleWidget;
      } else {
        return KqInkWell(
          onTap: () {
            onTapTitle?.call();
          },
          enableRipple: false,
          child: titleWidget,
        );
      }
    } else {
      return KqDropDownMenu(
        menuController: menuController ?? KqDropDownMenuController(),
        maxQty: 6,
        menuData: dropMenuData!,
        onSelected: (menuData) {
          onSelected?.call(menuData);
        },
        child: KqInkWell(
          onTap: () {
            onTapTitle?.call();
          },
          enableRipple: false,
          child: titleWidget,
        ),
      );
    }
  }

  double appBarHeight() {
    return 40;
  }
}
